本指南說明如何通過網絡在服務器之間共享文件。NFS 代表網絡文件系統,可用于通過附加的文件系統在本地訪問遠程服務器的數據。此示例由 2 臺服務器組成,其中一臺將充當主機 (storage1),第二臺將充當客戶端 (storage2),文件系統將從主機附加到該客戶端。
連接到主機和客戶端并安裝 nfs-utils 包。
CentOS 上的 NFS:
[root@storage1 ~]# yum -y install nfs-utils [root@storage2 ~]# yum -y install nfs-utils
Ubuntu/Debian 上的 NFS:
[root@storage1 ~]# yum -y install nfs-common [root@storage2 ~]# yum -y install nfs-common
創建一個將與客戶端-服務器共享的目錄。如果已經創建,則跳過此步驟。
[root@storage1 ~]# mkdir -p /home/data
為共享文件夾分配權限和所有權。
[root@storage1 ~]# chmod -R 755 /home/data/ [root@storage1 ~]# chown nfsnobody:nfsnobody /home/data/
啟動 NFS 服務
[root@storage1 ~]# systemctl enable rpcbind [root@storage1 ~]# systemctl enable nfs-server 創建了從 /etc/systemd/system/multi-user.target.wants/nfs-server.service 到 /usr/lib/systemd/system/nfs-server.service 的符號鏈接。 [root@storage1 ~]# systemctl enable nfs-lock [root@storage1 ~]# systemctl enable nfs-idmap [root@storage1 ~]# systemctl start rpcbind [root@storage1 ~]# systemctl start nfs-server [root@storage1 ~]# systemctl start nfs-lock [root@storage1 ~]# systemctl start nfs-idmap
通過編輯文件 /etc/exports 定義將與哪個客戶端共享的文件夾
[root@storage1 ~]# vi /etc/exports
在這種情況下,文件的內容將如下所示,其中 181.215.247.22 是客戶端-服務器公共 IP 地址。
/home/data 181.215.247.22(rw,sync,no_root_squash)
重新啟動 NFS 服務。
[root@storage1 ~]# systemctl restart nfs-server
在客戶端-服務器中選擇共享文件夾將被掛載的目錄或創建一個新文件夾。
[root@storage2 ~]# mkdir -p /home/mystorage/
將文件系統從主機附加到客戶端。
[root@storage2 ~]# mount -t nfs 2.58.28.45:/home/data /home/mystorage/
檢查文件系統是否附加成功。
[root@storage2 ~]# df -h 已使用的文件系統大小可用使用百分比已安裝在 devtmpfs 185M 0 185M 0% /dev tmpfs 209M 0 209M 0% /dev/shm tmpfs 209M 8.8M 200M 5%/運行 tmpfs 209M 0 209M 0% /sys/fs/cgroup /dev/sda1 10G 2.0G 8.1G 20% / tmpfs 42M 0 42M 0% /run/user/0 2.58.28.45:/home/data 10G 2.1G 8.0G 21% /home/mystorage
我們在主機服務器中有一個文本文件:
[root@storage1 ~]# cat /home/data/file.txt 此文本文件存在于 storage1 中
現在可以在客戶端-服務器中本地訪問它:
[root@storage2 ~]# cat /home/mystorage/file.txt 此文本文件存在于 storage1 中
為了在客戶端-服務器重新啟動后保持文件系統掛載,在文件 /etc/fstab 底部添加以下行,其中 2.58.28.45 是主機服務器公共 IP 地址。
2.58.28.45:/home/data /home/mystorage nfs 默認 0 0